package org.geektimes.projects.userweb.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.geektimes.projects.userweb.dao.AppUserDao;
import org.geektimes.projects.userweb.dao.entity.AppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @Author: jipeng
 * @Description:
 * @Date: Created in 2021/5/8 7:03
 */
@Service
public class UserDBService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    @Autowired
//    private SqlSessionFactory sqlSessionFactory;
//
//
//    @Cacheable(cacheNames = "cache_user", key = "'user_'+ #id", unless = "#result == null")
//    public AppUser getUser(Long id) {
//        AppUser user = null;
//        try(SqlSession sqlSession = sqlSessionFactory.openSession()){
//            AppUserDao userMapper =  sqlSession.getMapper(AppUserDao.class);
//            user = userMapper.selectUser(id);
//
//        }
//
//        logger.info("{} 查询的结果为 ：{}", id, user == null ? "null" : user.toString());
//        return user;
//    }


    @Autowired
    private AppUserDao appUserDao;


    @Cacheable(cacheNames = "cache_user", key = "'user_'+ #id", unless = "#result == null")
    public AppUser getUser(Long id) {
        AppUser user = appUserDao.selectUser(id);

        logger.info("{} 查询的结果为 ：{}", id, user == null ? "null" : user.toString());
        return user;
    }


    @CacheEvict(cacheNames = "cache_user", key = "'user_'+ #id")
    public String delUser(Long id) {
        logger.info("{} 缓存删除成功", id);
        return "执行成功";
    }
}
